/**
 * Copyright(c) 2010 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-5-29 下午3:00 Created by lyyang
 */
package com.jade.framework.web.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.jade.framework.base.security.AbstractPrincipal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 权限检查jsp tag
 *
 * @author lyyang
 * @version 1.0 13-5-29 下午3:00
 */
public class PermissionTag
        extends BodyTagSupport
{
    private String permission;
    private boolean notMode = false;

    public String getPermission()
    {
        return permission;
    }

    public void setPermission(String permission)
    {
        this.permission = permission;
    }

    public boolean isNotMode()
    {
        return notMode;
    }

    public void setNotMode(boolean notMode)
    {
        this.notMode = notMode;
    }

    public int doStartTag()
            throws JspException
    {
        String[] permissions = null;
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

        AbstractPrincipal user = ((AbstractPrincipal) request.getUserPrincipal());
        if (user == null) {
            return SKIP_BODY;
        }

        //对初始化的admin管理员 不做权限判断
        if (user.isSuperman()) {
            return notMode ? SKIP_BODY : EVAL_BODY_INCLUDE;
        }

        if (permission == null || permission.trim().equals("")) {
            return EVAL_BODY_INCLUDE;
        }
        int orFlag = permission.indexOf("||");
        if (orFlag == -1) {
            //and 模式
            permissions = permission.split(",");
            for (String permission1 : permissions) {
                if (!request.isUserInRole(permission1)) {

                    return notMode ? EVAL_BODY_INCLUDE : SKIP_BODY;
                }
            }
            return notMode ? SKIP_BODY : EVAL_BODY_INCLUDE;
        }
        else {
            //or  模式
            permissions = permission.split("[|][|]");
            for (String permission1 : permissions) {
                if (request.isUserInRole(permission1)) {
                    return notMode ? SKIP_BODY : EVAL_BODY_INCLUDE;
                }
            }
        }

        return notMode ? EVAL_BODY_INCLUDE : SKIP_BODY;
    }
}
